package com.viphuli.app.tool.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;

import com.loopj.android.http.RequestParams;
import com.offroader.utils.JsonUtils;
import com.offroader.utils.StringUtils;
import com.offroader.utils.ViewUtils;
import com.viphuli.app.tool.R;
import com.viphuli.app.tool.bean.PageBaseBean;
import com.viphuli.app.tool.bean.page.ArrangeActionPage;
import com.viphuli.app.tool.bean.part.AccountUser;
import com.viphuli.app.tool.bean.part.ArrangeType;
import com.viphuli.app.tool.common.AccessTokenKeeper;
import com.viphuli.app.tool.common.MyPageHelper;
import com.viphuli.app.tool.handler.ArrangeWeekViewResponseHandler.DayUserArrangeHolder;
import com.viphuli.app.tool.http.ApiRequest;
import com.viphuli.app.tool.utils.ImageUtils;
import com.viphuli.app.tool.utils.OtherUtils;

/**
 * 换班
 * 
 * @author li.li
 *
 */
public class ArrangeActionReplaceFragment extends BaseProgressFragment {

	@Bind(R.id.id_home_item_icon_bg)
	protected View iconBg;

	@Bind(R.id.id_home_item_icon_img)
	protected ImageView iconImg;

	@Bind(R.id.id_home_item_icon_name)
	protected TextView iconName;

	@Bind(R.id.id_home_item_name)
	protected TextView name;

	@Bind(R.id.id_home_item_from_user_img)
	protected ImageView fromUserImg;

	@Bind(R.id.id_home_item_from_user_name)
	protected TextView fromUserName;

	@Bind(R.id.id_home_item_to_user_img)
	protected ImageView toUserImg;

	@Bind(R.id.id_home_item_to_user_name)
	protected TextView toUserName;

	private DayUserArrangeHolder dayUserArrangeHolder;

	private AccountUser toUser;//当前选择的用户

	//替班操作确定结果集
	private List<Integer> arrangeIds = new ArrayList<Integer>();

	//某人某一天的排班信息
	private List<DayUserArrangeHolder> dayUserArrangeHolderList = new ArrayList<DayUserArrangeHolder>();

	//排班类型列表
	private List<ArrangeType> arrangeTypeList;

	@Override
	protected int obtainContentRes() {
		return R.layout.frag_arrange_action_replace;
	}

	@Override
	protected void initParams() {

		String dayUserArrangeHolderJson = getArguments().getString("day_user_arrange_holder");
		dayUserArrangeHolder = JsonUtils.fromJson(dayUserArrangeHolderJson, DayUserArrangeHolder.class);

		//加入排班操作集
		dayUserArrangeHolderList.add(dayUserArrangeHolder);

	}

	@Override
	protected void initView() {

	}

	@Override
	protected void initData() {

		AccountUser user = dayUserArrangeHolder.getUser();//当前用户

		List<ArrangeType> arrangeTypeList = dayUserArrangeHolder.getArrangeTypeList();
		ArrangeType targetArrangeType = null;
		if (arrangeTypeList.size() > 1) {
			targetArrangeType = arrangeTypeList.get(dayUserArrangeHolder.getCheck());
		} else {
			targetArrangeType = arrangeTypeList.iterator().next();
		}

		if (targetArrangeType != null) {

			name.setText(targetArrangeType.getName());
			ImageUtils.load(iconImg, targetArrangeType.getIcon());
			ViewUtils.setRadiusBg(iconBg, targetArrangeType.getColor());
			iconName.setText("替班");

		}

		fromUserName.setText(user.getUserName());
		ImageUtils.load(fromUserImg, user.getPortrait());

		//获得排班分类信息
		AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());
		if (tokenKeeper.isLogin()) {

			RequestParams params = new RequestParams();
			params.put("circle_id", tokenKeeper.getUser().circleId());
			ApiRequest.arrangeActionReplaceTypeList.request(this, params, false);

		}

	}

	public void setToUser(AccountUser toUser) {
		this.toUser = toUser;

		toUserName.setText(toUser.getUserName());
		ImageUtils.load(toUserImg, toUser.getPortrait());

		//加入排班操作集
		dayUserArrangeHolderList.add(new DayUserArrangeHolder(toUser, arrangeTypeList, dayUserArrangeHolder.getDate()));
	}

	@OnClick(R.id.id_home_item_from_user_layout)
	public void clickToUser() {
		
		//成员列表
		CircleMemberDialogFragment dialogFrag = new CircleMemberDialogFragment();
		dialogFrag.show(getChildFragmentManager(), dialogFrag.getClass().getSimpleName());

	}

	@OnClick(R.id.id_arrange_btn_replace)
	public void clickReplace() {

		arrangeReplace(dayUserArrangeHolder);
	}

	/**
	 * 执行替班操作
	 * @param dayUserArrangeHolder
	 */
	private void arrangeReplace(DayUserArrangeHolder dayUserArrangeHolder) {
		
		if(this.toUser == null){
			ViewUtils.toast("请选择替换人");
			return;
		}

		AccountUser toUser = dayUserArrangeHolder.getUser();
		Date date = dayUserArrangeHolder.getDate();
		
		AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());

		if (tokenKeeper.isLogin()) {

			RequestParams params = new RequestParams();

			if (arrangeIds.size() == 0) {

				params.put("uid", tokenKeeper.getOpenId());
				params.put("to_uid", toUser.getUid());
				params.put("time", OtherUtils.maxLength(date.getTime()));
				params.put("circle_id", tokenKeeper.getUser().circleId());
				params.put("type", 3);//1排班,2换班,3替班

				if (arrangeTypeList != null || !arrangeTypeList.isEmpty()) {
					for (ArrangeType type : this.arrangeTypeList) {
						if (type.getType() == 2) {//免费的类型
							params.put("arrange_type_id", type.getId());
							break;
						}
					}
				}

			} else if (arrangeIds.size() == 1) {

				params.put("uid", tokenKeeper.getOpenId());
				params.put("to_uid", toUser.getUid());
				params.put("time", OtherUtils.maxLength(date.getTime()));
				params.put("circle_id", tokenKeeper.getUser().circleId());
				params.put("type", 3);//1排班,2换班,3替班

				DayUserArrangeHolder targetDayUserArrangeHolder = dayUserArrangeHolderList.get(0);
				List<ArrangeType> targetArrangeTypeList = targetDayUserArrangeHolder.getArrangeTypeList();

				ArrangeType targetArrangeType = null;
				if (targetArrangeTypeList.size() > 1) {
					targetArrangeType = targetArrangeTypeList.get(targetDayUserArrangeHolder.getCheck());
				} else {
					targetArrangeType = targetArrangeTypeList.iterator().next();
				}

				params.put("arrange_type_id", targetArrangeType.getId());

			}

			ApiRequest.arrangeActionReplace.request(this, params);

		}

	}

	@Override
	public void onRequestResonse(PageBaseBean page) {
		super.onRequestResonse(page);

		//操作结果记录
		ArrangeActionPage actionPage = (ArrangeActionPage) page;
		arrangeIds.add(actionPage.getArrangeInfo().getId());

		if (arrangeIds.size() == 1) {//触发换班&替班

			DayUserArrangeHolder dayUserArrangeHolder = dayUserArrangeHolderList.get(1);
			arrangeReplace(dayUserArrangeHolder);

		} else if (arrangeIds.size() == 2) {//触发完成

			arrangeExchangeConfirm();

		}
	}

	/**
	 * 确定（替班）
	 */
	public void arrangeExchangeConfirm() {
		if (arrangeIds.isEmpty() || arrangeIds.size() != 2) {
			return;
		}

		if (dayUserArrangeHolderList.size() == 2) {

			AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());

			if (tokenKeeper.isLogin()) {

				StringBuilder arrangeIdBuider = new StringBuilder();

				for (int i = 0; i < arrangeIds.size(); i++) {

					if (i != 0)
						arrangeIdBuider.append(",");

					arrangeIdBuider.append(arrangeIds.get(i));

				}

				RequestParams params = new RequestParams();
				params.put("uid", tokenKeeper.getOpenId());
				params.put("arrange_info_ids", arrangeIdBuider.toString());
				params.put("type", 3);//1：排班，2：调班，3：替班
				params.put("circle_id", tokenKeeper.getUser().circleId());
				params.put("remark", StringUtils.EMPTY);

				ApiRequest.arrangeActionConfirm.request(this, params);
			}

		}
	}

	public void setArrangeTypeList(List<ArrangeType> arrangeTypeList) {
		this.arrangeTypeList = arrangeTypeList;
	}

	public List<DayUserArrangeHolder> getDayUserArrangeHolderList() {
		return dayUserArrangeHolderList;
	}

	public static void go(Activity act, Bundle args) {
		MyPageHelper.arrangeActionReplace.showMyPage(act, args);
	}

}
